package com.dailyblue.java.project.power.service.impl;

import com.dailyblue.java.project.power.bean.JsonResult;
import com.dailyblue.java.project.power.bean.Powers;
import com.dailyblue.java.project.power.bean.Users;
import com.dailyblue.java.project.power.mapper.UsersMapper;
import com.dailyblue.java.project.power.service.PowersService;
import com.dailyblue.java.project.power.service.UsersService;
import com.dailyblue.java.project.power.util.ResultCode;
import com.dailyblue.java.project.power.util.ResultTool;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.util.List;

@Service
public class UsersServiceImpl implements UsersService {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private PowersService powersService;

    @Override
    public JsonResult<Users> login(String userName, String password, String sessionId, ServletContext application) {
        Users user = usersMapper.login(userName, password);
        if (user == null) {
            return ResultTool.fail(ResultCode.USER_CREDENTIALS_ERROR);
        }
        long time = System.currentTimeMillis();
        sessionId = sessionId + time;
        user.setSessionId(sessionId);
        application.setAttribute(sessionId, user);
        return ResultTool.success(user);
    }

    @Override
    public JsonResult<String> uniqueName(String name) {
        int count = usersMapper.uniqueName(name);
        if (count == 0) {
            return ResultTool.success(ResultCode.SUCCESS);
        }
        return ResultTool.success(ResultCode.COMMON_FAIL);
    }

    @Override
    public JsonResult<Users> saveUser(Users user, String sessionId, ServletContext application) {
        usersMapper.saveUser(user);
        return login(user.getUserName(), user.getPassword(), sessionId, application);
    }

    @Override
    public int checkUsersHasPermission(int uid, String url) {
        return usersMapper.checkUsersHasPermission(uid, url);
    }

    @Override
    public void updateUserByRole(int rid, int uid) {
        usersMapper.updateUserByRole(rid, uid);
    }

    @Override
    public JsonResult<List<Users>> findAllUsers() {
        return ResultTool.success(usersMapper.findAllUsers());
    }

    @Override
    public JsonResult<List<Powers>> updateUserPower(int uid, int[] pid) {
        // 删除这个用户的所有权限
        usersMapper.deleteUserPower(uid);
        // 添加新的权限
        for (int i = 0; i < pid.length; i++) {
            usersMapper.saveUserPower(uid,pid[i]);
        }
        // 返回这个用户的权限
        return powersService.findPowerByUserId(uid);
    }
}
